<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/26
 * Time: 14:58
 */

namespace App\Wechat\Remind\Logics;

use App\Exceptions\ApiException;
use App\Exceptions\Error;
use App\Wechat\Remind\Models\Remind as RemindModel;
use Illuminate\Support\Facades\DB;

class Remind extends Base
{
	public function listRemind($page_no = 1, $page_size = 10)
	{
		$RemindModel = RemindModel::query()->where([
			['openid', '=', $this->user->openid],
			['is_deleted', '=', 0]
		]);
		$total_num = $RemindModel->count();
		$total_page = ceil($total_num / $page_size);
		$data = $RemindModel->orderByDesc('date')
			->orderBy('time')
			->orderByDesc('created_at')
			->select(['id', 'title', 'content', DB::raw('DATE_FORMAT(date, "%m-%d") as date, DATE_FORMAT(time, "%H:%i") as time'), 'status'])
			->offset(($page_no-1) * $page_size)
			->limit($page_size)
			->get()
			->groupBy('date');
		return [
			'count' => $total_num,
			'total_page' => $total_page,
			'page_size' => $page_size,
			'cur_page' => $page_no,
			'data' => $data
		];
	}
	public function showRemind($id)
	{
		$remind = RemindModel::query()->where([
			['id', '=', $id],
			['openid', '=', $this->user->openid]
		])
			->select(['id', 'title', 'content', 'date', 'time', 'wx_remind', 'tel_remind', 'status'])
			->first();
		if (!$remind) {
			throw new ApiException('未找到提醒事项', Error::PARAMS_ERROR);
		}
		return $remind;
	}

	public function createRemind(array $remind)
	{
		$remind = array_merge($remind, [
			'openid' => $this->user->openid
		]);
		return RemindModel::query()->create($remind);
	}

	public function editRemind($id, array $remind)
	{
		$old_remind = RemindModel::query()->where([
			['id', '=', $id],
			['openid', '=', $this->user->openid],
			['is_deleted', '=', 0]
		])->first();
		if (!$old_remind){
			throw new ApiException('未找到提醒事项', Error::PARAMS_ERROR);
		}
		return RemindModel::query()->where('id', $id)->update($remind);
	}

	public function deleteRemind($id)
	{
		$old_remind = RemindModel::query()->where([
			['id', '=', $id],
			['openid', '=', $this->user->openid],
			['is_deleted', '=', 0]
		])->first();
		if (!$old_remind){
			throw new ApiException('未找到提醒事项', Error::PARAMS_ERROR);
		}
		return RemindModel::query()->where('id', $id)->update(['is_deleted' => 1]);
	}

	public function countRemind()
	{
		$count = RemindModel::query()->where([
			['openid', '=', $this->user->openid],
			['is_deleted', '=', 0]
		])
			->select([DB::raw('
				count(date = "'. date('Y-m-d') .'" or null) as today, 
				count(*) as total, 
				count(date < "'. date('Y-m-d') .'" or null) as finish
			')])
			->get();
		return $count[0];
	}
}